package com.jeecg.demo.controller;
import com.jeecg.demo.entity.GlCarEntity;
import com.jeecg.demo.entity.ShopsEntity;
import com.jeecg.demo.entity.SysOrderVerifyEntity;
import com.jeecg.demo.service.GlCarServiceI;
import com.jeecg.demo.service.SysOrderVerifyServiceI;
import com.jeecg.demo.util.GetUserTenantId;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.common.TreeChildCount;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import java.io.OutputStream;
import org.jeecgframework.core.util.BrowserUtils;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jeecgframework.core.util.ResourceUtil;
import java.io.IOException;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.util.Map;
import java.util.HashMap;
import org.jeecgframework.core.util.ExceptionUtil;


import org.jeecgframework.web.cgform.entity.upload.CgUploadEntity;
import org.jeecgframework.web.cgform.service.config.CgFormFieldServiceI;
import java.util.HashMap;
/**   
 * @Title: Controller  
 * @Description: GL_CAR
 * @author onlineGenerator
 * @date 2018-11-28 11:43:05
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/glCarController")
public class GlCarController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(GlCarController.class);

	@Autowired
	private GlCarServiceI glCarService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private CgFormFieldServiceI cgFormFieldService;
	@Autowired
	private SysOrderVerifyServiceI sysOrderVerifyService;
	


	/**
	 * GL_CAR列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request,String type) {
		request.setAttribute("type", type);
		return new ModelAndView("com/jeecg/demo/glCarList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(GlCarEntity glCar,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid,String type) {
		CriteriaQuery cq = new CriteriaQuery(GlCarEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, glCar, request.getParameterMap());
		try{
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		if ("shenpi".equals(type)) {
			cq.eq("reqstate", "1");
			cq.add();
		}
		GetUserTenantId getuserfun=new GetUserTenantId();
//		String idString = String.valueOf(systemService.findOneForJdbc(getuserfun.getSql(),getuserfun.getOrgcode()).get("worktypeid"));  
//		int worktypeid = Integer.parseInt(idString);
//		System.out.println("--------tenantidcar"+worktypeid);
//		cq.eq("worktypeid", worktypeid);
		cq.add();
		this.glCarService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * 删除GL_CAR
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(GlCarEntity glCar, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		glCar = systemService.getEntity(GlCarEntity.class, glCar.getId());
		message = "删除成功";
		try{
			glCarService.delete(glCar);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除GL_CAR
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "删除成功";
		try{
			for(String id:ids.split(",")){
				GlCarEntity glCar = systemService.getEntity(GlCarEntity.class, 
				id
				);
				glCarService.delete(glCar);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加GL_CAR
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(GlCarEntity glCar, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "添加成功";
		try{
			glCarService.save(glCar);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		j.setObj(glCar);
		return j;
	}
	
	/**
	 * 更新GL_CAR
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(GlCarEntity glCar, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "更新成功";
		GlCarEntity t = glCarService.get(GlCarEntity.class, glCar.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(glCar, t);
			glCarService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	

	/**
	 * GL_CAR新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(GlCarEntity glCar, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(glCar.getId())) {
			glCar = glCarService.getEntity(GlCarEntity.class, glCar.getId());
			req.setAttribute("glCarPage", glCar);
		}
		return new ModelAndView("com/jeecg/demo/glCar-add");
	}
	/**
	 * GL_CAR编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(GlCarEntity glCar, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(glCar.getId())) {
			glCar = glCarService.getEntity(GlCarEntity.class, glCar.getId());
			req.setAttribute("glCarPage", glCar);
			req.setAttribute("action", "glCarController.do?doUpdate");
			
		}
		return new ModelAndView("com/jeecg/demo/glCar-update");
	}
	
	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name","glCarController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(GlCarEntity glCar,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(GlCarEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, glCar, request.getParameterMap());
		List<GlCarEntity> glCars = this.glCarService.getListByCriteriaQuery(cq,false);
		modelMap.put(NormalExcelConstants.FILE_NAME,"车源信息");
		modelMap.put(NormalExcelConstants.CLASS,GlCarEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("车源信息", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
			"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,glCars);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(GlCarEntity glCar,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
    	modelMap.put(NormalExcelConstants.FILE_NAME,"GL_CAR");
    	modelMap.put(NormalExcelConstants.CLASS,GlCarEntity.class);
    	modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("GL_CAR列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
    	"导出信息"));
    	modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList());
    	return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<GlCarEntity> listGlCarEntitys = ExcelImportUtil.importExcel(file.getInputStream(),GlCarEntity.class,params);
				for (GlCarEntity glCar : listGlCarEntitys) {
					glCarService.save(glCar);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(e.getMessage());
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
	
	/**
	 * 获取文件附件信息
	 * 
	 * @param id glCar主键id
	 */
	@RequestMapping(params = "getFiles")
	@ResponseBody
	public AjaxJson getFiles(String id){
		List<CgUploadEntity> uploadBeans = cgFormFieldService.findByProperty(CgUploadEntity.class, "cgformId", id);
		List<Map<String,Object>> files = new ArrayList<Map<String,Object>>(0);
		for(CgUploadEntity b:uploadBeans){
			String title = b.getAttachmenttitle();//附件名
			String fileKey = b.getId();//附件主键
			String path = b.getRealpath();//附件路径
			String field = b.getCgformField();//表单中作为附件控件的字段
			Map<String, Object> file = new HashMap<String, Object>();
			file.put("title", title);
			file.put("fileKey", fileKey);
			file.put("path", path);
			file.put("field", field==null?"":field);
			files.add(file);
		}
		AjaxJson j = new AjaxJson();
		j.setObj(files);
		return j;
	}
	
	
	/**
	 * GLCAR审核页面跳转
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(params = "goVerify")
	public ModelAndView goVerify(GlCarEntity glCar, HttpServletRequest req)
			throws Exception {
		if (StringUtil.isNotEmpty(glCar.getId())) {
			GlCarEntity t = glCarService.get(GlCarEntity.class, glCar.getId());
		
			req.setAttribute("glCarPage", t);
			req.setAttribute("action", "glCarController.do?doVerify");
		}
		return new ModelAndView("com/jeecg/demo/glCar-update");
	}

	/**
	 * 审核GLCAR
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doVerify")
	@ResponseBody
	public AjaxJson doVerify(GlCarEntity glCar, HttpServletRequest req,
			String verifyflag, String verifynote) {
		String message = null;
		AjaxJson j = new AjaxJson();

		GlCarEntity t = glCarService.get(GlCarEntity.class, glCar.getId());
		TSUser u = ResourceUtil.getSessionUser();
		String beforestatus = "";
		try {
			// 根据认证申请状态判断审核前状态
			
			if (t.getReqstate().equals("1")) {
				beforestatus = "0";
			} else if (t.getReqstate().equals("2")) {
				beforestatus = "1";
			} else if (t.getReqstate().equals("3")) {
				beforestatus = "1";
			}

			// 设置审核记录
			SysOrderVerifyEntity verify = new SysOrderVerifyEntity();
//			GlCarEntity verify = new GlCarEntity();
			int i=t.getSysid();
			verify.setOrdid(i);
			verify.setOrdtype("CARVERIFY");
			verify.setBeforestatus(beforestatus);
			verify.setVerifyuserid(0);
			verify.setVerifynote(verifynote);
			verify.setVerifytime(new Date());
			verify.setOrderid(1);

			if ("true".equals(verifyflag)) {
				message = "审核成功";

				if (null != verifynote && !verifynote.equals("")) {
					message += "\r\n审核意见:" + verifynote;
				}

				// 保存审核记录
				verify.setVerifystatus("2");
				sysOrderVerifyService.save(verify);

				// 保存状态
				t.setReqstate("2");
				glCarService.saveOrUpdate(t);

				systemService.addLog(message, Globals.Log_Type_OTHER,
						Globals.Log_Leavel_INFO);
			} else if ("false".equals(verifyflag)) {
				message = "审核退回";

				if (null != verifynote && !verifynote.equals("")) {
					message += "\r\n退回原因:" + verifynote;
				}

				// 保存审核记录
				verify.setVerifystatus("3");
				sysOrderVerifyService.save(verify);

				// 保存状态
				t.setReqstate("3");
				glCarService.saveOrUpdate(t);

				systemService.addLog(message, Globals.Log_Type_OTHER,
						Globals.Log_Leavel_INFO);
			}

		} catch (Exception e) {
			e.printStackTrace();
			message = "审核失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	
	
}
